
import ParentView from '@/components/ParentView/index.vue';
// 匹配views里面所有的.vue文件
const modules = import.meta.glob('../views/**/*.vue')


export function generateRoutes(menus){
  const res = []
  for (const menu of menus) {
    // 处理路由
    const route = {
      //id: menu.id,
      path: menu.path,
      name: menu.name+menu.path,
      // 动态加载视图
      component: loadView(menu.component),
      meta: {
        title: menu.name,
        icon: menu.icon
      }
    }
    // 如果有子菜单
    if (menu.children && menu.children.length > 0) {
      // 递归处理子菜单
      route.children = generateRoutes(menu.children)
      // 默认重定向到第一个子路由
      if (menu.children[0]) {
        route.redirect = menu.children[0].path
      }
      //顶级菜单，需要父视图作为跳板
      if(!menu.component){
        route.component = ParentView
      }
    }
    res.push(route)
  }
  return res
}

/**
 * 动态加载视图组件
 * @param {String} viewPath 组件路径，如 'views/user/index'
 */
export const loadView =  (view) => {
  let res = null
    for (const path in modules) {
      const dir = path.split('views/')[1].split('.vue')[0]
      if (dir === view) {
        res = () => modules[path]()
      }
    }
    return res;
}